import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLAvailability {

    private static int state = -1;

    public static final Logger logger = LoggerFactory.getLogger(URLAvailability.class);

    /**
     * 功能：获取网络请求数据,
     * 描述：最多连接网络 2 次, 如果 2 次都不成功，视为该地址不可用
     *
     * @param urlStr 指定URL网络地址
     * @return URL
     */
    public static String getResultFromURL(String urlStr) {
        URL url;
        HttpURLConnection con = null;
        InputStream inputStream = null;

        int counts = 0;
        if (urlStr == null || urlStr.length() <= 0) {
            return null;
        }
        while (counts < 2) {
            try {
                url = new URL(urlStr);
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET"); // 设置请求方式
                con.setConnectTimeout(30000);
                state = con.getResponseCode();
                if (state == 200) {
                    inputStream = con.getInputStream();
                    return IOUtils.toString(inputStream, "UTF-8");
                }else{
                    return null;
                }
            } catch (Exception ex) {
                logger.error(ex.toString());
                counts++;
                logger.error("URL不可用，连接第 " + counts + " 次");
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
                if (con != null) {
                    con.disconnect();
                }
            }
        }
        return null;
    }
}
